import { OmsCartItem } from "@/entity/OmsCartItem";
import { OmsCartItemCreationParam } from "@/entity/OmsCartItemCreationParam";
import { Page } from "@/entity/Page";
import { ResponseResult } from "@/entity/ResponseResult";
import { AxiosError, AxiosResponse } from "axios";
import httpClient from "./http-client";
import store, { TOKEN_USER_ID } from "@/store";
import { db_cartItems } from "@/database/cart";
import { db_product } from "@/database/product";

export class CartItemService {
    baseUrl = "/api/v1.0/portal/cart-item";

    public async page(no = 1, size = 10): Promise<Page<OmsCartItem>> {
        const userId = Number(store.getters[TOKEN_USER_ID]);
        const res = db_cartItems.filter(it => it.memberId == userId).filter((it, idx) => {
            return idx >= (no - 1) * size && idx < no * size;
        });
        return Promise.resolve({
            "content": res,
            "pageable": {
                "sort": {
                    "empty": false,
                    "sorted": true,
                    "unsorted": false
                },
                "offset": 0,
                "pageNumber": no - 1,
                "pageSize": size,
                "unpaged": false,
                "paged": true
            },
            "totalElements": db_cartItems.length,
            "last": true,
            "totalPages": db_cartItems.length / size + 1,
            "size": 10,
            "number": no,
            "sort": {
                "empty": false,
                "sorted": true,
                "unsorted": false
            },
            "numberOfElements": res.length,
            "first": true,
            "empty": false
        });
        // 前端从1开始计数，后端从0开始计数
        no = no - 1;
        return httpClient.get(`${this.baseUrl}?page=${no}&size=${size}`).then((res: AxiosResponse<ResponseResult<Page<OmsCartItem>>>) => {
            if (res.data.data) {
                const page = res.data.data;
                // 前端从1开始计数，后端从0开始计数
                page.number = page.number + 1;
                return Promise.resolve(page);
            } else {
                throw "no data";
            }
        });
    }

    public async query(ids: number[] = []): Promise<OmsCartItem[]> {
        return Promise.resolve(db_cartItems.filter(it => ids.includes(it.id)));

        return httpClient.get(`${this.baseUrl}/query?ids=${ids.join(",")}`).then((res) => {
            if (res.data.data) {
                return Promise.resolve(res.data.data);
            } else {
                throw "no data";
            }
        });
    }

    public async createOrUpdate(param: OmsCartItemCreationParam) {
        const userId = Number(store.getters[TOKEN_USER_ID]);
        if (param.productId == null || param.quantity == null) {
            throw new AxiosError();
        }
        let item = db_cartItems.find(it => it.memberId == userId && it.productId == param.productId);
        if (item != null) {
            item.quantity = item.quantity == null ? param.quantity : item.quantity + param.quantity;
        } else {
            const product = db_product.find(it => it.id == param.productId);
            if (product == null) {
                throw new AxiosError();
            }
            item = new OmsCartItem();
            item.memberId = userId;
            item.id = Math.max(...db_cartItems.map(it => it.id)) + 1;
            item.quantity = param.quantity;
            item.productId = product.id;
            item.price = product.price;
            item.productImgUrl = product.imgUrl;
            item.productName = product.name;

            db_cartItems.push(item);
        }

        return Promise.resolve({
            "code": 200,
            "message": "操作成功",
            "data": item.id
        });

        const body = {
            ...param
        }
        return httpClient.post(`${this.baseUrl}`, body).then((res: AxiosResponse<ResponseResult<number>>) => {
            if (res.data.data) {
                const id = res.data.data;
                return Promise.resolve(id);
            } else {
                throw "no data";
            }
        });
    }

    public async remove(ids: number[] = []): Promise<OmsCartItem[]> {
        const tmp = db_cartItems.filter(it => !ids.includes(it.id));
        db_cartItems.length = 0;
        db_cartItems.push(...tmp);

        return Promise.resolve([]);

        return httpClient.delete(`${this.baseUrl}?ids=${ids.join(",")}`).then((res) => {
            if (res.data.data) {
                return Promise.resolve(res.data.data);
            } else {
                throw "no data";
            }
        });
    }
}

const instance = new CartItemService();
export default instance;